package com.zhongwang.mms.module.purchase.service;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.zhongwang.mms.common.JsonResult;
import com.zhongwang.mms.gen.entity.TWarehouseInfo;
import com.zhongwang.mms.gen.entity.User;
import com.zhongwang.mms.module.purchase.dao.PurChangeDao;
import com.zhongwang.mms.module.purchase.dao.PurlnvQueryDao;
import com.zhongwang.mms.module.purchase.model.PChangeOrderModel;
import com.zhongwang.mms.module.purchase.model.PurInvQueryModel;
import com.zhongwang.mms.module.purchase.model.PurWarQueryModel;
import com.zhongwang.mms.module.system.log.LogService;
import com.zhongwang.mms.util.ExportExcelUtils;
import com.zhongwang.mms.util.FileUtils;
import com.zhongwang.mms.util.ShiroUtils;
import lombok.extern.log4j.Log4j2;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @ClassName： AllocationManageService
 * @Description： 库存查询业务逻辑层
 * @Author： China.zh
 * @Date： 2020/4/6 13:41
 * @Version： V1.0
 **/
@Log4j2
@Service
public class PurlnvQueryService {

    @Autowired
    private PurlnvQueryDao purlnvQueryDao;
    @Autowired
    private PurChangeDao purChangeDao;
    @Autowired
    private LogService logService;
    @Value("${user.upload.path}")
    private String uploadPath;

    /**
     * findPurInvList
     * 加载库存列表以及综合查询
     *
     * @param param 查询条件
     * @return
     */
    public List<PurInvQueryModel> findPurInvList(PurInvQueryModel param) {
        List<PurInvQueryModel> list = null;
        try {
            list = purlnvQueryDao.selectByParam(param);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return list;
    }

    /**
     * findPurInvList
     * 加载库存列表用于串料使用
     *
     * @param param 查询条件
     * @return
     */
    public List<PurInvQueryModel> findPurChangeListInvList(PurInvQueryModel param) {
        List<PurInvQueryModel> list = null;
        try {
            list = purlnvQueryDao.findPurChangeListInvList(param);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 获取外购件专用仓库列表
     */
    public List<TWarehouseInfo> findWarehouseInfoListByPurchase() {
        return purlnvQueryDao.findWarehouseInfoListByPurchase();
    }

    @Value("${spring.profiles.active}")
    private String active;

    /**
     * 列表 导出
     *
     * @param param 查询条件
     * @return list
     */
    public JsonResult exportExcel(PurInvQueryModel param) throws IOException {
        // 记录开始时间（纳秒）
        long startTime = System.nanoTime();
        JsonResult jsonResult = new JsonResult();
        //获取当前用户
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        //存储/读取Excel的文件夹的路径 mms文件夹下/用户账户/
        String path = uploadPath + user.getAccount() + "/";
        String excelFileName = "外购件库库存查询列表.xlsx";
        if (param.getTitle()==null || param.getTitle().equals("")){
            param.setTitle("外购件库库存查询");
        }
        logService.saveLog(param.getTitle()+"——导出","用户:【"+user.getName()+"】开始执行导出操作！");
        try {
            //1.创建临时内存表名
            String tempTableName = "##" + user.getAccount() + (UUID.randomUUID().toString().replace("-", ""));
            param.setTempTableName(tempTableName);
            Subject userSubject = ShiroUtils.getSubject();
            //2.查询出数据导入到临时表
            if (userSubject.isPermitted("purinv:amount:view")) {
                purlnvQueryDao.createWarQueryTempTable2(param);
            } else {
                purlnvQueryDao.createWarQueryTempTable2NotMoney(param);
            }
            //3.导出Excel
           if(ExportExcelUtils.BuildExcel(path, excelFileName, tempTableName, active,true)){
               jsonResult.setData(excelFileName);
               jsonResult.setType(JsonResult.ResultType.SUCCESS);
           }else{
               jsonResult.setType(JsonResult.ResultType.ERROR);
           }
        } catch (Exception e) {
            log.debug(e.getMessage());
            e.printStackTrace();
            jsonResult.setType(JsonResult.ResultType.ERROR);
        }
        // 记录结束时间
        long endTime = System.nanoTime();
        // 计算耗时（秒）
        double elapsedSeconds = (endTime - startTime) / 1_000_000_000.0;
        logService.saveLog(param.getTitle()+"——导出","用户:【"+user.getName()+"】执行导出操作完成，耗时"+elapsedSeconds+"秒！");
        return jsonResult;
    }

    /**
     * @FunctionName: findPInventoryChangeOrderList
     * @Description: 查看该库存的串料信息，来自于哪个物料
     * @Author: 徐一贺
     * @CreateDate: 2020/6/13 15:11
     * @Phone: 18241927380
     * @Param: []
     * @Return: com.zhongwang.mms.common.JsonResult
     * @Throw:
     * @Version: v 1.0.0
     */
    public List<PChangeOrderModel> findPInventoryChangeOrderList(PChangeOrderModel param) {
        return purChangeDao.findPInventoryChangeOrderList(param);
    }
}
